<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 抽奖 tian 212
 */
class Gifts extends Api
{
    protected $noNeedLogin = ['gifts_setting'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     *
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 科室列表
     *
     * @ApiMethod (POST)
     * @param string $pid
     */
    public function department_list()
    {
        $Articles= new \app\common\model\Articles;
        $Category= new \app\common\model\Category;
        $pid = $this->request->post('pid',21);
        $data_one=$Category->where("pid=".$pid." and deletetime is null")->select();
        foreach($data_one as $key=>$value){
            $data_one[$key]["sons"]=$Category->where("pid=".$value["id"])->select();
        }

        $this->success("获取成功", $data_one);
    }

    //所有奖项展示列表
    public function show_gifts_list(){

        $Gifts= new \app\common\model\Gifts;
        $Giftslist= new \app\common\model\Giftslist;
        $ShoproOrder= new \app\common\model\ShoproOrder;
        $Giftssetting= new \app\common\model\Giftssetting;
        $Giftscannum= new \app\common\model\Giftscannum;
        $ShoproGoods= new \app\common\model\ShoproGoods();
        $Manghe= new \app\common\model\Manghe;
        $User= new \app\common\model\User();
        $uid = $this->auth->id;


        $result=$Gifts
//            ->alias("giftslist")
//            ->join('fa_gifts gifts','gifts.id =  giftslist.gifts_id', 'LEFT')
//            ->join('fa_shopro_goods g','g.id =  gifts.goods_id', 'LEFT')
//            ->field("giftslist.*,g.id as goods_id,g.title,g.subtitle,gifts.type,gifts.money")
            ->where("delete_time is  null")
            ->select();


        $time_seting=$Giftssetting->where("id=1")
            ->find();
        $now_time=$time_seting["begin_time"];
        $end_time=$time_seting["end_time"];

        //var_dump($uid);
        $this_limit_yeji=$ShoproOrder
            ->where("user_id=".$uid." and (status=1 or status=2) and type='goods' and FROM_UNIXTIME(createtime) >='".$now_time."' and FROM_UNIXTIME(createtime)<='".$end_time."'")
            ->sum("pay_fee");
        //->buildSql();


        $is_can_choujiang=false;
        $gifts_can_num=collection($Giftscannum->order("money asc")->select())->toArray();
        /*$this_gifts_canget_num=0;
        foreach($gifts_can_num as $key=>$value){
            if($value["money"]<=$this_limit_yeji && $already_choujiang_nums<$value["can_get_num"]){//本次的业绩 和次数满足 抽奖标准
                $is_can_choujiang=true;
                $this_gifts_canget_num=$value["can_get_num"];
            }
        }*/
        $userD = \app\common\model\User::get($uid);
        $this_gifts_canget_num = $userD['chou_num'];
        $already_choujiang_nums=$Giftslist->where("uid=".$uid)->count();//该用户已经抽的次数
        $can_num=$this_gifts_canget_num-$already_choujiang_nums;//剩余可抽奖次数
        if($can_num<0){
            $can_num=0;
        }
        //如果是商品或者盲盒 返回关联的商品图片
        foreach ($result as $key=>$value){//奖项类型 0 ：现金奖  1：商品奖 2盲盒奖  3：谢谢惠顾
            if($value["type"]==1){
                $result[$key]["goods"]=$ShoproGoods->where("id=".$value["goods_id"])->find();
            }
        }

        $this->success_gift("获取成功", $result,null,null,array(),$can_num);
    }


    //转盘抽奖
    public function get_gift(){
        $uid = $this->request->post('uid');
        $token = $this->request->post('token', '');
        $openid=$this->request->post('openid');
        $uid = $this->auth->id;

        //var_dump(55555);die;
        $Gifts= new \app\common\model\Gifts;
        $Giftslist= new \app\common\model\Giftslist;
        $ShoproUserWalletLog= new \app\common\model\ShoproUserWalletLog();
        $ShoproOrder= new \app\common\model\ShoproOrder;
        $Giftssetting= new \app\common\model\Giftssetting;
        $Giftscannum= new \app\common\model\Giftscannum;
        $ShoproGoods= new \app\common\model\ShoproGoods();
        $Manghe= new \app\common\model\Manghe;
        $User= new \app\common\model\User();
        //$now_time=date("Y-m-d H:i:s",time());
        //$end_time="2022-01-20 23:59:59";
        $time_seting=$Giftssetting->where("id=1")
            ->find();
        $now_time=$time_seting["begin_time"];
        $end_time=$time_seting["end_time"];

        if($now_time>=$end_time){
            $this->error("活动已结束,期待与你再次相遇");
        }
        if(empty($uid)){
            $this->error("缺少必要参数");
        }
        if(!empty($uid)){

            //var_dump($uid);;die;
            $thi_fa_user=$User->where("id=".$uid)->find();
            if(empty($thi_fa_user)){
                $this->error("该登录用户不存在");
            }

            //计算当前抽奖时间区间的订单业绩开始
            $this_limit_yeji=$ShoproOrder
                ->where("user_id=".$uid." and (status=1 or status=2) and type='goods' and FROM_UNIXTIME(createtime) >='".$now_time."' and FROM_UNIXTIME(createtime)<='".$end_time."'")
                ->sum("pay_fee");
            //->buildSql();
            //var_dump($this_limit_yeji);die;
            $already_choujiang_nums=$Giftslist->where("uid=".$uid)->count();//该用户已经抽的次数
            //var_dump($already_choujiang_nums);
            //计算当前抽奖时间区间的订单业绩结束
            $is_can_choujiang=false;
            $gifts_can_num=collection($Giftscannum->order("money asc")->select())->toArray();
            foreach($gifts_can_num as $key=>$value){
                if($value["money"]<=$this_limit_yeji && $already_choujiang_nums<$value["can_get_num"]){//本次的业绩 和次数满足 抽奖标准
                    $is_can_choujiang=true;
                    $this_gifts_canget_num=$value["can_get_num"];
                }
            }
            if($is_can_choujiang==false){
                $this->error("订单业绩尚未到达抽奖标准!");
            }
            //var_dump($gifts_can_num);die;
            $already_choujiang_nums=$Giftslist->where("uid=".$uid)->count();//该用户已经抽的次数
            $userD = \app\common\model\User::get($uid);
            if($already_choujiang_nums >= $userD['chou_num']){
                $this->error('抽奖次数已用完');
            }
            //拼装奖项数组
            // 奖项id，奖品，概率
            $prize_arr=collection($Gifts->where(" delete_time is null")->select())->toArray();
            //var_dump($prize_arr);
//            $prize_arr = array(
//                '0' => array('id'=>1,'prize'=>'福利一: 开通会员即可赠送永久使用权限','v'=>7),
//                '1' => array('id'=>2,'prize'=>'福利二: 开通会员即可赠送爆款产品《客源汇电脑版》','v'=>4),
//                '2' => array('id'=>3,'prize'=>'福利三: 开通会员即可赠送价值1280元的搜企业','v'=>4),
//                '3' => array('id'=>4,'prize'=>'福利四: 开通会员即可赠送599元置顶推广','v'=>4),
//                '4' => array('id'=>5,'prize'=>'福利五: 开通会员即可赠送---附近客源','v'=>4),
//            );
            //var_dump($prize_arr);die;
            foreach ($prize_arr as $key => $val) {
                $arr[$val['id']] = $val['percentage'];//概率数组
            }
            $rid = $this->get_rand($arr); //根据概率获取奖项id
            //var_dump($rid);
            //var_dump($prize_arr);die;
            //$res['yes'] = $prize_arr[$rid-1]['gifts_name']; //中奖项
            $zhongjiang=$Gifts->where("id=".$rid)->find();
            $res['yes'] =$zhongjiang["gifts_name"]; //中奖项
            //$res['level'] = $prize_arr[$rid-1]['id']; //几等奖 tianadd

            //var_dump($res['yes']);die;
//            unset($prize_arr[$rid-1]); //将中奖项从数组中剔除，剩下未中奖项
//            shuffle($prize_arr); //打乱数组顺序
//            for($i=0;$i<count($prize_arr);$i++){
//                $pr[] = $prize_arr[$i]['gifts_name']; //未中奖项数组
//            }
            //$res['no'] = $pr;
             //var_dump($res);die;
            if($res['yes']!='所有'){//中奖

                //中奖后记录中奖记录开始
                //$get_res55 = $Gifts->where("(gift_level is  null or gift_level='') and type=1 and openid="."'$openid'")->find();
                //var_dump($get_res55);die;
                $data["addtime"]=date("Y-m-d H:i:s",time());
                $data["gifts_id"]=$rid;
                $data["gift_name"]=$res['yes'];
                $data["uid"]=$uid;
                if($zhongjiang["type"]==2){
                    $suiji_manghe=$Manghe->alias("m")
                        ->join('fa_shopro_goods g','g.id =  m.goods_id', 'LEFT')
                        ->field("g.*,m.id as manghe_id,m.goods_id as manghe_goods_id")
                        ->orderRaw('rand()')->limit(1)->find();
                    $data["manghe_id"]=$suiji_manghe["manghe_id"];
                }
                //$data["type"]=1;//抽奖活动类别区分  0:第一次抽奖活动  1：辞旧迎新虎年大吉活动
                $addres=$Giftslist->insertGetId($data);
                //var_dump($addres);die;

                //中奖后记录中奖记录结束

                $result['status']=1;
                $result['gifts_id']=$rid;
                $result['name']=$res['yes'];
                $result['type']=$zhongjiang["type"];//奖项类型 0 ：现金奖  1：商品奖 2盲盒奖
                $result['money']=$zhongjiang["money"];
                if($result['type']==0){//0 ：现金奖
                    $result['goods']="";
                    //现金奖 累加金额开始
                    $memo="现金奖";
                    $User::money($zhongjiang["money"],$uid,$memo);

                    //插入 fa_shopro_user_wallet_log 表日志
                    $data_user_wallet_log["user_id"]=$uid;
                    $data_user_wallet_log["wallet"]=$zhongjiang["money"];
                    $data_user_wallet_log["wallet_type"]="money";
                    $data_user_wallet_log["type"]="get_gifts";
                    $data_user_wallet_log["before"]=$thi_fa_user["money"];
                    $data_user_wallet_log["after"]=$thi_fa_user["money"]+$zhongjiang["money"];
                    $data_user_wallet_log["memo"]="抽奖现金奖红包";
                    $data_user_wallet_log["oper_type"]="user";
                    $data_user_wallet_log["oper_id"]=$uid;
                    $data_user_wallet_log["createtime"]=time();
                    $data_user_wallet_log["updatetime"]=time();
                    $ShoproUserWalletLog->insertGetId($data_user_wallet_log);
                    //UserWalletLog::write($user, $money, $before, $after, $type, $type_id, "money", $memo, $ext);

                }elseif($result['type']==1 && !empty($zhongjiang["goods_id"])){
                    //$result['goods']=$ShoproGoods->where("id=".$zhongjiang["goods_id"])->find();
                    $result['goods']=$this->detail($zhongjiang["goods_id"]);
                }elseif($result['type']==2){//盲盒奖 随机去选商品
                    //$result['goods']=$suiji_manghe;
                    $result['goods']=$this->detail($suiji_manghe["manghe_goods_id"]);
                }else{
                    $result['goods']="";
                }

                $this_gifts_canget_num =  $userD['chou_num'];
                $result['can_num']=$this_gifts_canget_num-$already_choujiang_nums-1;//剩余可抽奖次数

            }
            $this->success("抽奖成功", $result);
        }else{
            $this->error("缺少必要参数");
        }

    }


    //商品详情  他们给  让按照这个格式返回
    public function detail($id)
    {

        //$id = $this->request->get('id');

        $detail = \addons\shopro\model\Goods::getGoodsDetail($id);

        // 记录足记
        \addons\shopro\model\UserView::addView($detail);

        $sku_price = $detail['sku_price'];      // 处理过的规格
        // tp bug json_encode 或者 toArray 的时候 sku_price 会重新查询数据库，导致被处理过的规格又还原回去了
        $detail = json_decode(json_encode($detail), true);
        if(!empty($detail['sku_price'])){
            //var_dump($detail['sku_price'][0]);;die;
            $detail['sku_price'][0]["real_price"]=$detail['sku_price'][0]["price"];
            $detail['sku_price'][0]["price"]="0";
        }
        //$detail['sku_price'] = $detail['sku_price'];

        return  $detail;
        $this->success('商品详情', $detail);
    }


    //我的抽奖列表
    public function gifts_list(){

        $Gifts= new \app\common\model\Gifts;
        $Giftslist= new \app\common\model\Giftslist;
        $ShoproOrder= new \app\common\model\ShoproOrder;
        $Giftssetting= new \app\common\model\Giftssetting;
        $Giftscannum= new \app\common\model\Giftscannum;
        $ShoproGoods= new \app\common\model\ShoproGoods();
        $Manghe= new \app\common\model\Manghe;
        $User= new \app\common\model\User();
        $uid = $this->auth->id;

        if(empty($uid)){
            $this->error("缺少必要参数");
        }
        if(!empty($uid)) {

            $thi_fa_user = $User->where("id=" . $uid)->find();
            if (empty($thi_fa_user)) {
                $this->error("该登录用户不存在");
            }
        }
        $result=$Giftslist->alias("giftslist")
            ->join('fa_gifts gifts','gifts.id =  giftslist.gifts_id', 'LEFT')
            ->join('fa_shopro_goods g','g.id =  gifts.goods_id', 'LEFT')
            ->where("uid=".$uid)
            ->field("giftslist.*,g.id as goods_id,g.title,g.subtitle,g.price,g.image,g.images,g.sales,gifts.type,gifts.money")
            ->select();
        foreach ($result as $key=>$value){
            if($value["manghe_id"]>0){
                $t_manghe=$Manghe->where("id=".$value["manghe_id"])->find();
                //var_dump();die;
                $m_55[$key]=$ShoproGoods->where("id=".$t_manghe["goods_id"])->find();
                $result[$key]["title"]=$m_55[$key]["title"];
                $result[$key]["goods_id"]=$t_manghe["goods_id"];
                $result[$key]["price"]=$m_55[$key]["price"];
                $result[$key]["image"]=$m_55[$key]["image"];
                $result[$key]["images"]=$m_55[$key]["images"];
                $result[$key]["sales"]=$m_55[$key]["sales"];
            }

        }
        $this->success("获取成功", $result);
    }


    //抽奖时间/描述
    public function gifts_setting(){

        $Gifts= new \app\common\model\Gifts;
        $Giftslist= new \app\common\model\Giftslist;
        $ShoproOrder= new \app\common\model\ShoproOrder;
        $Giftssetting= new \app\common\model\Giftssetting;
        $Giftscannum= new \app\common\model\Giftscannum;
        $ShoproGoods= new \app\common\model\ShoproGoods();
        $Manghe= new \app\common\model\Manghe;
        $User= new \app\common\model\User();
        $thi_fa_user = $Giftssetting->where("id=1")->find();
        $this->success("获取成功", $thi_fa_user);
    }


    //计算中奖概率
    public function get_rand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        // var_dump($proSum);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum); //返回随机整数

            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }


    /**
     * 省市区列表
     *
     * @ApiMethod (POST)
     * @param string $pid
     */
    public function area_list()
    {
        $ShoproArea= new \app\common\model\ShoproArea;
        $pid = $this->request->post('pid',0);
        $data_one=$ShoproArea->where("pid=".$pid)->select();
        foreach($data_one as $key=>$value){
            $data_one[$key]["sons_two"]=$ShoproArea->where("pid=".$value["id"])->select();
            if(!empty($data_one[$key]["sons_two"])){
                foreach($data_one[$key]["sons_two"] as $key2=>$value2){
                    //var_dump($value2["id"]);
                    $data_one[$key]["sons_two"][$key2]["sons_thr"]=$ShoproArea->where("pid=".$value2["id"])->select();
                    //$yyy=$ShoproArea->where("pid=".$value2["id"])->select();
                    //var_dump($yyy);die;
                }
            }
        }
        $this->success("获取成功", $data_one);
    }

    /**
     * 获取全国省市区列表（格式化后）
     */
    public function getRegionList()
    {
        $ShoproArea= new \app\common\model\ShoproArea;
        $data = $ShoproArea->select()->toArray();
        var_dump($data);die;
        $data = $this->assembleRegionData($data);
        return $data;
    }


    /**
     * 重组地区数据
     */
    public function assembleRegionData($data, $pid = 0)
    {
        $list = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                // 继续查找其子市区县
                $v['list'] = $this->assembleRegionData($data, $v['id']);
                // 如果子地区为空，则unset掉
                if (empty($v['list'])) {
                    unset($v['list']);
                }
                $list[] = $v;
            }
        }
        return $list;
    }

    /**
     * 首页banner图
     *
     * @ApiMethod (POST)
     * @param string $department_id  科室类别id
     */
    public function index_banner()
    {
        $Doctor= new \app\common\model\Doctor;
        $ShoproDecorateContent= new \app\common\model\ShoproDecorateContent;
        $decorate_id = $this->request->post('decorate_id',1);
        if(empty($decorate_id)){
            $this->error("模板id必传");
        }
        $data=$ShoproDecorateContent
//            ->alias("a")
//            ->join("fa_category c", "c.id = a.category_id", "LEFT")
//            ->where("type="."'banner' and decorate_id=".$decorate_id." and id=13")
            ->where("type="."'banner' and decorate_id=".$decorate_id)
//            ->field("a.*, c.name type_name")
            ->order("id asc")
            ->select();
        if(!empty($data)){
            $data=$data[0];
        }
        $this->success("获取成功", $data);
    }


    /**
     * 医生列表
     *
     * @ApiMethod (POST)
     * @param string $department_id  科室类别id
     */
    public function doctor_lists()
    {
        //var_dump(88888);die;
        $Doctor= new \app\common\model\Doctor;
        $Category= new \app\common\model\Category;
        $department_id = $this->request->post('department_id');
        $keyword= $this->request->post('keyword');
        $province = $this->request->post('province');
        $city = $this->request->post('city');
        $area = $this->request->post('area');


        $page =$this->request->request("page", 0);
        $limit = $this->request->request("limit", 10);
        if(empty($limit)) $limit = 10;
        if($limit > 20) $limit = 20;
        $offset = $page * $limit;


        $where["a.delete_time"]=null;
        $where_string= "a.delete_time is null";
        if(!empty($department_id)){
           $where["a.department_id"]=$department_id;
        }
        if(!empty($keyword)){
            $where_string=$where_string." and ( doctor_name like '%".$keyword."%' or doctor_position like '%".$keyword."%' or hospital_name like '%".$keyword."%'  or doctor_tags like '%".$keyword."%' )";

//            $where_string=$where_string."doctor_name like ";
//            $where['doctor_name']  = array('like',"%$keyword%");
        }
        if(!empty($province)){
            $province = mb_ereg_replace("市", "", $province);
            $province = mb_ereg_replace("县", "", $province);
            $where["a.province"]=$province;
        }
        if(!empty($city)){
            $where["a.city"]=$city;
        }
        if(!empty($area)){
            $where["a.area"]=$area;
        }

        $all_num=$Doctor
            ->alias("a")
            ->join("fa_category c", "c.id = a.department_id", "LEFT")
            ->where($where)
            ->where($where_string)
            ->field("a.*, c.name type_name")
            ->count();

        $data=$Doctor
            ->alias("a")
            ->join("fa_category c", "c.id = a.department_id", "LEFT")
            ->where($where)
            ->where($where_string)
            ->field("a.*, c.name type_name")
            ->order("id desc")
            ->limit("$offset, $limit")
            ->select();
        foreach($data as $key=>$value){
            if(empty($value["type_name"])){
                $data[$key]["type_name"]="";
            }
        }
        //$this->success("获取成功", $data);
        $this->success55("获取成功",$data,1,null,array(),$all_num);
        $this->success("获取成功", $data);
    }


    /**
     * 首页搜索列表
     *
     * @ApiMethod (POST)
     * @param string $department_id  科室类别id
     */
    public function index_search()
    {
        $Doctor= new \app\common\model\Doctor;
        $Category= new \app\common\model\Category;
        $Articles= new \app\common\model\Articles;
        $ShoproGoods= new \app\common\model\ShoproGoods;
        $keyword= $this->request->post('keyword');
        $area = $this->request->post('area');
        $where["deletetime"]=null;
        $where_doc["a.delete_time"]=null;
        $where_art["delete_time"]=null;
        $where_string_goods= "deletetime is null";
        $where_string_doc= "a.delete_time is null";
        $where_string_art= "delete_time is null";
        if(!empty($keyword)){
            $where_string_doc=$where_string_doc." and ( doctor_name like '%".$keyword."%' or doctor_position like '%".$keyword."%' or hospital_name like '%".$keyword."%'  or doctor_tags like '%".$keyword."%' )";
        }
        if(!empty($keyword)){
            $where_string_goods=$where_string_goods." and ( title like '%".$keyword."%' or subtitle like '%".$keyword."%')";
        }

        if(!empty($keyword)){
            $where_string_art=$where_string_art." and ( title like '%".$keyword."%')";
        }
        $data["goods"]=$ShoproGoods
//            ->alias("a")
//            ->join("fa_shopro_goods_sku k", "k.goods_id = a.id", "LEFT")
            ->where($where)
            ->where($where_string_goods)
            //->field("a.*, k.name ku_name")
            ->order("id desc")
            ->limit(2)
            ->select();
//        foreach($data["goods"] as $key=>$value){
//            $data["goods"][$key]["sku"]=Db::table("fa_shopro_goods_sku")
//                ->where("goods_id=".$value["id"])
//                ->order("id desc")
//                ->select();
//        }
        $data["doctor"]=$Doctor
            ->alias("a")
            ->join("fa_category c", "c.id = a.department_id", "LEFT")
            ->where($where_doc)
            ->where($where_string_doc)
            ->field("a.*, c.name type_name")
            ->order("id desc")
            ->limit(2)
            ->select();
        foreach($data["doctor"] as $key=>$value){
            if(empty($value["type"])){
                $data["doctor"][$key]["type_name"]="";
            }
        }
        $data["article"]=$Articles
//            ->alias("a")
//            ->join("fa_category c", "c.id = a.category_id", "LEFT")
            ->where($where_art)
            ->where($where_string_art)
//            ->field("a.*, c.name type_name")
            ->order("id desc")
            ->limit(2)
            ->select();

        $this->success("获取成功", $data);
    }


    /**
     * 医生详情
     *
     * @ApiMethod (POST)
     * @param string $id  医生id
     */
    public function doctor_detail()
    {
        $Articles= new \app\common\model\Articles;
        $Category= new \app\common\model\Category;
        $Doctor= new \app\common\model\Doctor;
        $id = $this->request->post('id');
        if(empty($id)){
            $this->error("医生id必传");
        }
        $data=$Doctor->where("a.id=".$id." and delete_time is null")
            ->alias("a")
            ->join("fa_category c", "c.id = a.department_id", "LEFT")
            ->field("a.*, c.name type_name")
            ->order("id desc")
            ->find();
        if(empty($data["type_name"])){
            $data["type_name"]="";
        }

        $this->success("获取成功", $data);
    }



}
